var gulp = require("gulp"),
    gutil = require("gulp-util"),
    webpack = require("webpack"),
    WebpackDevServer = require("webpack-dev-server"),
    webpackConfig = require("./webpack.config.js"),
    HtmlWebpackPlugin = require('html-webpack-plugin'),
    webConfig = require("./webconfig.json"),
    path = require("path"),
    uglify = require("gulp-uglify"),
    clean = require('gulp-clean'),
    concat = require('gulp-concat'),
    rename = require('gulp-rename');

//默认
gulp.task("default", ["webpack-dev-server"], function() {
    setTimeout(function() {
        gulp.start("build-dev");
    }, 1000);
});

//开发环境
gulp.task("build-dev", ["webpack:build-dev", "vendor-minifyjs"], function() {
    gulp.start('clean-task');
    gulp.watch(["app/**/*"], ["webpack:build-dev"]);
});

gulp.task("webpack:build-dev", function(callback) {
    var config = Object.create(webpackConfig);
    config.plugins = [];
    //可以根据修改的contollers修改
    var pages = [];
    webConfig.modules.forEach(function(m) {
        if (m.edited == 'true') {
            pages.push(m.name);
        }
    });
    //var pages = ['home', 'member'];
    pages.forEach(function(name) {
        var plugin = new HtmlWebpackPlugin({
            filename: '../' + (name == 'home' ? 'index' : name) + '.html',
            template: '../assets/' + name + '.html',
            hash: true,
            inject: true,
            minify: { removeAttributeQuotes: true, removeScriptTypeAttributes: true, removeComments: true, collapseWhitespace: true },
            chunks: [name]
        });
        config.plugins.push(plugin);
    });

    webpack(config, function(err, stats) {
        if (err) throw new gutil.PluginError("webpack:build-dev", err);
        gutil.log("[webpack:build-dev]", stats.toString({
            colors: true
        }));
        callback();
    });
});

//生产环境
gulp.task("build", ["webpack:build", "vendor-minifyjs"], function() {
    gulp.start('clean-task');
});

gulp.task("webpack:build", function(callback) {
    //console.log(webpackConfig);
    var config = Object.create(webpackConfig);
    config.plugins = [];
    config.plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            warnings: false
        },
        mangle: false
    }));
    var pages = [];
    webConfig.modules.forEach(function(m) {
        if (m.edited == 'true') {
            pages.push(m.name);
        }
    });
    pages.forEach(function(name) {
        var plugin = new HtmlWebpackPlugin({
            filename: '../' + (name == 'home' ? 'index' : name) + '.html',
            template: '../assets/' + name + '.html',
            hash: true,
            inject: true,
            minify: { removeAttributeQuotes: true, removeScriptTypeAttributes: true, removeComments: true, collapseWhitespace: true },
            chunks: [name]
        });
        config.plugins.push(plugin);
    });
    webpack(config, function(err, stats) {
        if (err) throw new gutil.PluginError("webpack:build", err);
        gutil.log("[webpack:build]", stats.toString({
            colors: true
        }));
        callback();
    });
});

gulp.task('vendor-minifyjs', ['jq-plugins', 'vendor-min'], function(callback) {
    callback();
});

//删除合并文件夹
gulp.task('clean-task', function(callback) {
    gulp.src('./vendor', {
            read: false
        })
        .pipe(clean());
    callback();
});

//合并jQuery插件
gulp.task('jq-plugins', function(callback) {
    // gulp.src('./app/vendor/jquery.*.js')
    gulp.src([
            './app/vendor/jquery.min.js',
            './app/vendor/jquery.pjax.min.js',
            './app/vendor/jquery.cookie.min.js'
        ])
        .pipe(concat('jquery.js'))
        .pipe(gulp.dest('./vendor'))
        .pipe(rename({
            suffix: '.min'
        }))
        // .pipe(uglify({
        //     compress: false,
        //     mangle: false
        // }))
        .pipe(gulp.dest('./dist'));
    callback();
});

//压缩public
gulp.task('vendor-min', function(callback) {
    // gulp.src('./app/vendor/public/*.js')
    gulp.src([
            './app/vendor/public/knockout-min.js',
            './app/vendor/public/underscore-min.js',
            './app/vendor/public/template.js',
            './app/vendor/public/moment.min.js',
            './app/vendor/public/mustache.min.js',
            './app/vendor/public/handlebars.min.js'
        ])
        .pipe(concat('vendor.js'))
        .pipe(gulp.dest('./vendor'))
        .pipe(rename({
            suffix: '.min'
        }))
        // .pipe(uglify({
        //     compress: false,
        //     mangle: false
        // }))
        .pipe(gulp.dest('./dist'));
    callback();
});

//压缩IE低版本浏览器JS文件库
gulp.task('ie-min', function(callback) {
    gulp.src([
            './app/vendor/public/dd_belatedpng.min.js',
            './app/vendor/public/json2.min.js'
        ])
        .pipe(concat('ie.js'))
        .pipe(gulp.dest('./vendor'))
        .pipe(rename({
            suffix: '.min'
        }))
        .pipe(gulp.dest('./dist'));
    callback();
});

//压缩dist文件
// gulp.task('dist-min', function() {
//     gulp.src([".dist/*.js", ".dist/!jquery.*.js", ".dist/!vendor.*.js"])
//         .pipe(gulp.dest(webpackConfig.output.path));
// });

//本地开发调试
gulp.task("webpack-dev-server", function(callback) {
    var config = Object.create(webpackConfig);
    config.devtool = "eval";
    config.debug = true;

    new WebpackDevServer(webpack(config), {
        publicPath: "/dev-server",
        stats: {
            colors: true
        }
    }).listen(9003, "localhost", function(err) {
        if (err) throw new gutil.PluginError("webpack-dev-server", err);
        gutil.log("[webpack-dev-server]", "http://localhost:9003/webpack-dev-server/index.html");
        callback();
    });
});